package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.stream.Collectors;

@Component
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
@Slf4j
public class SupplyTaskHandler implements MsgHandler {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String jsonMsg) {

        try {
            //解析
            SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
            //被指派人
            String innerCode = supplyContract.getInnerCode();
            VmVO vmInfo = vmService.getVMInfo(innerCode);
            int user = taskService.getLeastUser(vmInfo.getRegionId(), false);
            //创建补货工单
            TaskViewModel taskViewModel = new TaskViewModel();
            taskViewModel.setUserId(user);
            taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
            taskViewModel.setDesc("自动补货工单");
            taskViewModel.setCreateType(0);
            taskViewModel.setInnerCode(innerCode);
            //工单详情
            taskViewModel.setDetails(supplyContract.getSupplyData().stream().map(
                    s -> {
                        TaskDetailsViewModel taskDetailsViewModel = new TaskDetailsViewModel();
                        taskDetailsViewModel.setChannelCode(innerCode);

                        taskDetailsViewModel.setExpectCapacity(s.getCapacity());
                        taskDetailsViewModel.setSkuId(s.getSkuId());
                        taskDetailsViewModel.setSkuName(s.getSkuName());
                        taskDetailsViewModel.setSkuImage(s.getSkuImage());

                        return taskDetailsViewModel;
                    }
            ).collect(Collectors.toList()));

            taskService.createTask(taskViewModel);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("创建补货工单出错" + e.getMessage());
        }

    }
}
